package com.gedeshidai.shumadevelop.service.impl;


import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gedeshidai.shumadevelop.common.BaseResponse;
import com.gedeshidai.shumadevelop.common.ErrorCode;
import com.gedeshidai.shumadevelop.common.ResultUtils;
import com.gedeshidai.shumadevelop.constant.CommonConstant;
import com.gedeshidai.shumadevelop.exception.BusinessException;
import com.gedeshidai.shumadevelop.mapper.ProductMapper;
import com.gedeshidai.shumadevelop.mapper.UserMapper;
import com.gedeshidai.shumadevelop.model.dto.product.ProductProxyRequest;
import com.gedeshidai.shumadevelop.model.dto.product.ProductSelectRequest;
import com.gedeshidai.shumadevelop.model.entity.Product;
import com.gedeshidai.shumadevelop.model.entity.User;
import com.gedeshidai.shumadevelop.model.enums.UserRoleEnum;
import com.gedeshidai.shumadevelop.model.vo.UserVO;
import com.gedeshidai.shumadevelop.model.vo.ProductVO;
import com.gedeshidai.shumadevelop.service.ProductService;
import com.gedeshidai.shumadevelop.service.UserService;
import com.gedeshidai.shumadevelop.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author Romdon
 * @description 针对表【products(商品基本信息表)】的数据库操作Service实现
 * @createDate 2024-06-17 08:28:14
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements ProductService {
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public QueryWrapper<Product> getQueryWrapper(Product product, HttpServletRequest request) {
        if (product == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        Long productId = product.getProductId();
        String productName = product.getProductName();
        Date timeOn = product.getTimeOn();
        Date timeOff = product.getTimeOff();
        Long userId = product.getUserId();
        Integer productOnlineState = product.getProductOnlineState();
        productQueryWrapper.eq(ObjectUtils.isNotEmpty(productId), "product_id", productId);
        productQueryWrapper.eq(StringUtils.isNotBlank(productName), "product_name", productName);
        productQueryWrapper.eq(ObjectUtils.isNotEmpty(productOnlineState), "product_online_state", productOnlineState);
        productQueryWrapper.eq(ObjectUtils.isNotEmpty(timeOn), "DATE(time_on)", timeOn);
        productQueryWrapper.eq(ObjectUtils.isNotEmpty(timeOff), "DATE(time_off)",timeOff );
        productQueryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        User loginUser = userService.getLoginUser(request);
        if (!UserRoleEnum.ADMIN.getValue().equals(loginUser.getUserRole())){
            productQueryWrapper.and(i->i.eq(ObjectUtils.isNotEmpty(loginUser.getUserId()), "user_id", loginUser.getUserId()).or().like("user_proxy",loginUser.getUserAccount()));

        }
        return productQueryWrapper;
    }

    @Override
    public BaseResponse<Page<ProductVO>> SelectShoppingsDetailsList(ProductSelectRequest productSelectRequest, HttpServletRequest request) {
        Product productRequest = new Product();
        if (productSelectRequest==null||request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BeanUtils.copyProperties(productSelectRequest,productRequest);
        if (!StringUtils.isAnyBlank(productSelectRequest.getUserAccount())){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_account",productSelectRequest.getUserAccount());
            User user = userService.getOne(userQueryWrapper);
            productRequest.setUserId(user.getUserId());
        }

        Page<Product> productPage = this.page(new Page<>(productSelectRequest.getCurrent(), productSelectRequest.getPageSize()),
                getQueryWrapper(productRequest, request));
        List<Product> records = productPage.getRecords();
        Page<ProductVO> productVOPage = new Page<>(productPage.getCurrent(),productPage.getSize(),productPage.getTotal());
        ArrayList<ProductVO> productVOS = new ArrayList<>();
        for (Product product:records) {
            ProductVO productVO = ProductVO.objToVo(product);
            Long userId = product.getUserId();
            User user = userService.getById(userId);
            productVO.setUserVO(userService.getUserVO(user));
            productVOS.add(productVO);
        }
        productVOPage.setRecords(productVOS);
        return ResultUtils.success(productVOPage);
    }




    /**
     * 根据商品id查询代理人
     * @param
     * @return
     */
    @Override
    public BaseResponse<Page<UserVO>> getProxysById(ProductProxyRequest productProxyRequest) {
        if (productProxyRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long productId = productProxyRequest.getId();
        if (productId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String proxy = productMapper.getProxysById(productId);
        List<String> proxys= JSONUtil.toList(proxy,String.class);
        Page<UserVO> page = new Page<>(productProxyRequest.getCurrent(), productProxyRequest.getPageSize(), proxys.size());
        List<UserVO> userVOS=new ArrayList<>();
        for (int i = (productProxyRequest.getCurrent()-1)*productProxyRequest.getPageSize();
             i <productProxyRequest.getCurrent()*productProxyRequest.getPageSize() ; i++) {
            if (i>=proxys.size()){
                break;
            }
            String userAccount = proxys.get(i);
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_account",userAccount);
            UserVO userVO = userService.getUserVO(userService.getOne(userQueryWrapper));
            userVOS.add(userVO);
        }
        page.setRecords(userVOS);
        return ResultUtils.success(page);
    }

    /**
     * 从基本商品表中删除的代理人
     * @param proxys
     * @return
     */
    @Override
    public void deleteProxys(List<String> proxys,Long id) {
        String proxy = productMapper.getProxysById(id);
        List<String> BeforeproxyList=JSONUtil.toList(proxy,String.class);
        proxys.forEach(n->{
            BeforeproxyList.removeIf(s->n.equals(s));
        });
        String AfterproxyList=JSONUtil.toJsonStr(BeforeproxyList);
        productMapper.updateProxyById(AfterproxyList,id);
    }
    /**
     * 添加代理人
     * @param userAccount
     * @param id
     * @return
     */
    @Override
    public void addProxy(String userAccount, Long id) {
        if(userAccount==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断用户是否存在
        if(userMapper.getUserIdByProxy(userAccount)==null ){
            throw new BusinessException(ErrorCode.EXIST_ACCOUNT_ERROR);
        }
        String proxy = productMapper.getProxysById(id);
        //已经存在的代理人
        List<String> proxyList=JSONUtil.toList(proxy,String.class);
        if(proxyList.contains(userAccount)){
            throw new BusinessException(ErrorCode.EXIST_PROXY_ERROR);
        }
        proxyList.add(userAccount);
        String AfterproxyList=JSONUtil.toJsonStr(proxyList);
        productMapper.updateProxyById(AfterproxyList,id);
    }
}




